import { routerRedux } from 'dva';
import { loginAdmin, loginTeacher, loginGeneral, getRoleList } from '../service';
import $$ from 'cmn-utils';
import { noticeGlobal } from "@/utils/core";

let LOADED = false;

export default {
  namespace: 'login',

  state: {
    loggedIn: false,
    message: '',
    user: {},
    roleList: []
  },

  subscriptions: {
    setup({ history, dispatch }) {
      return history.listen(({ pathname }) => {
        if (pathname.indexOf('/sign/login') !== -1) {
          $$.removeStore('user');
          $$.removeStore('token');
          if (!LOADED){
            LOADED = true;
            dispatch({
              type: 'init'
            });
          }
        }
      });
    }
  },

  effects: {
    // Enter Page load roles List
    *init({payload}, {call, put}){
      const {code, msg, data} = yield call(getRoleList);
      // console.log(status, msg, data);
      if (code == 200){
        yield put({
          type: 'setRoleList',
          payload: data,
        })
      }else{
        noticeGlobal.error({message: msg});
      }
    },

    *login({ payload }, { call, put }) {
      try {
        // const { status, message, data } = yield call(login, payload);
        // if (payload.userType == 'admin'){
        //   var { code, msg, data } = yield call(loginAdmin, payload);
        // }else if(payload.userType == 'teacher'){
        //   var { code, msg, data } = yield call(loginTeacher, payload);
        // }else {
        //   notice.error('未知用户类型');
        // }
        const {code, msg, data} = yield call(loginGeneral, payload);
        if (code === 200) {
          // $$.setStore('user', {'userName': payload.account});
          $$.setStore('token', data.token);
          // const token = $$.getStore('token')
          yield put(routerRedux.replace('/'));
        } else {
          noticeGlobal.error({message: msg, placement: 'bottomRight'});
          yield put({
            type: 'loginError',
            payload: { message: msg }
          });
        }
      } catch (e) {
        yield put({
          type: 'loginError',
          payload: { message: e.message }
        });
      }
    },
    *logout(_, { put }) { }
  },

  reducers: {
    setRoleList(state, {payload}){
      return {...state, roleList: payload}
    },
    loginSuccess(state, { payload }) {
      return {
        ...state,
        loggedIn: true,
        message: '',
        user: payload
      };
    },
    loginError(state, { payload }) {
      return {
        ...state,
        loggedIn: false,
        message: payload.message
      };
    }
  }
};
